package cn.project.lemontree.controller;

import cn.project.lemontree.aop.SystemControllerLog;
import cn.project.lemontree.bean.*;
import cn.project.lemontree.bean.Class;
import cn.project.lemontree.service.*;
import cn.project.lemontree.tools.CommonResult;
import cn.project.lemontree.utils.MyAuthenticationToken;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

@RestController
@CrossOrigin  //跨域访问
@RequestMapping("/administrator")
public class AdministratorController {

    @Resource
    private NoticeService noticeService;
    @Resource
    private ParentService parentService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private ClassService classService;
    @Resource
    private Online_sourceService online_sourceService;
    @Resource
    private AdministratorService administratorService;


    @ApiOperation(value = "管理员登录")
    @PostMapping("/ad_login")
    public CommonResult login(@RequestBody Administrator administrator){

        char[] pass = administrator.getPassword().toCharArray();
        MyAuthenticationToken token = new MyAuthenticationToken(administrator.getTelephone(),pass,2);
        Subject subject = SecurityUtils.getSubject();
        try{
            if(!subject.isAuthenticated()){
                subject.login(token);
            }
        }catch (UnknownAccountException e){
            return CommonResult.failed("用户名不存在");
        }catch (IncorrectCredentialsException e){
            return CommonResult.failed("密码不正确");
        }catch (AuthenticationException e){
            return CommonResult.failed();
        }
        return CommonResult.success(true);
    }

    @SystemControllerLog(description = "管理员发送公告")
    @ApiOperation(value = "发送公告")
    @PostMapping("/savenotice")
    public CommonResult saveNotice(@RequestBody tempNotice tempNotice){
        Notice notice = new Notice();
        notice.setContainer(tempNotice.getContainer());
        return CommonResult.success(noticeService.save(notice,tempNotice.getParent_ids(),tempNotice.getTeacher_ids()));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class tempNotice implements Serializable {
        String container;
        List<Integer> parent_ids;
        List<Integer> teacher_ids;
    }

    @ApiOperation(value = "查找对象")
    @GetMapping("/findSomeoneBytp")
    public CommonResult findSomeontBytp(@RequestParam("telephone") String telephone){
        User user = null;
        Parent parent = parentService.findBytp(telephone);
        Teacher teacher = teacherService.findBytp(telephone);
        if(parent != null){
            user = new User(parent);
            return CommonResult.success(user);
        }else if(teacher != null){
            user = new User(teacher);
            return CommonResult.success(user);
        }else{
            return CommonResult.failed("查无此人");
        }
    }

    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public CommonResult importExcel(@RequestParam("file") MultipartFile file,Integer classId) {
        try{
            if(file != null){
                String result = administratorService.importExcel(file,classId);
                if("200".equals(result)){
                    return CommonResult.success(true);
                }else{
                    return CommonResult.failed();
                }
            }else{
                return CommonResult.failed("empty");
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("异常");
        }
    }

    @GetMapping("/getcandp")
    public CommonResult<List<CandP>> getCAndP(){
        List<Class> classes = classService.getAllClass();
        List<CandP> list = new ArrayList<>();
        for(Class c : classes){
            List<Parent> parents = parentService.getByClassId(c.getClassId());
            List<Parent> ps = new ArrayList<>();
            Set<Integer> set = new HashSet<>();
            for(Parent parent :parents){
                if(!set.contains(parent.getParentId())){
                    set.add(parent.getParentId());
                    ps.add(parent);
                }
            }
            CandP candP = new CandP(c);
            candP.setChildren(ps);
            list.add(candP);
        }
        return CommonResult.success(list);
    }

    @GetMapping("/gett")
    public CommonResult<List<Teacher>> getT(){
        List<Teacher> list = teacherService.getAllTeachers();
        return CommonResult.success(teacherService.getAllTeachers());
    }

    @ApiOperation("分页查询管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="页码",required=true,dataTypeClass = int.class,example = "1"),
            @ApiImplicitParam(name="size",value="每页行数",required=true,dataTypeClass = int.class,example = "10"),
            @ApiImplicitParam(name="userName",value="管理员名称",required=false,dataTypeClass = String.class),
            @ApiImplicitParam(name="telephone",value="电话号码",required=false,dataTypeClass = String.class)
    })
    @GetMapping("/listpage")
    public CommonResult listpage(int page,int size,String userName,String telephone){
        Map<String,Object> map = new HashMap<>();
        map.put("count",administratorService.count(userName,telephone));
        map.put("data",administratorService.listPage(page,size,userName,telephone));
        return CommonResult.success(map);
    }

    @ApiOperation(value = "添加管理员信息")
    @PostMapping("/save")
    public CommonResult saveClass(@RequestBody Administrator administrator){
        return CommonResult.success(administratorService.save(administrator));
    }


    @ApiOperation(value = "修改管理员信息")
    @PostMapping("/update")
    public  CommonResult updateClass(@RequestBody Administrator administrator){
        return CommonResult.success(administratorService.update(administrator));
    }

    @PostMapping("/savesource")
    public CommonResult save(@RequestParam("file") MultipartFile file,String topic,String description){
        Online_source online_source = new Online_source(topic,description);
        return CommonResult.success(online_sourceService.save(file,online_source));
    }
}
